package com.cj.webapp_Start.sp_network

import com.google.gson.GsonBuilder
import com.cj.webapp_Start.sp_network.encryption.AESUtilsExt
import okhttp3.Response
import okio.Buffer
import java.nio.charset.Charset

val gson by lazy { GsonBuilder().disableHtmlEscaping().create() }

/**
 * 请求参数加密
 */
fun String.requestEncrypt(): String {
    return ParamsGenerator(this).buildRequestData()
}

/**
 * 返回数据解密
 */
fun Response.responseDecrypt(bodyData: String): String {
    return if (this.headers["X-Server-Encrypt"] == "1") {//是加密数据
        val buffer = Buffer()
        request.body?.writeTo(buffer)
        val bodyString = buffer.readString(Charset.forName("UTF-8"))
        val requestBody = gson.fromJson(bodyString, ParamsGenerator::class.java)
        return try {
            var newData = ""
            gson.fromJson<MutableMap<String, String>>(bodyData, Map::class.java)
                .let { responseData ->
                    AESUtilsExt.decryptBase64(
                        responseData["data"],
                        KeyMap.instance.getKey(requestBody.key ?: "")
                    )?.let { responseRealData ->
                        KeyMap.instance.remove(requestBody.key ?: "")
                        responseData["data"] = responseRealData
                        newData = gson.toJson(responseData)
                            .replace("\\\"", "\"")
                            .replace("\\\\", "\\")
                            .replace("\\", "")
                            .replace("\"{", "{")
                            .replace("}\"", "}")
                            .replace("\"[", "[")
                            .replace("]\"", "]")
                            .trim()
                    }
                }
            newData
        } catch (e: Throwable) {
            e.printStackTrace()
            ""
        }
    } else {
        bodyData
    }
}